import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/login/Login.vue'
import Chat from '../views/chat/Chat.vue'
import { useAuthStore } from '../stores/auth'

/**
 * 路由配置模块
 * 负责应用路由的定义、路由守卫和认证状态检查
 */

const routes = [
  {
    path: '/',
    redirect: '/chat'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresGuest: true }
  },
  {
    path: '/chat',
    name: 'Chat',
    component: Chat,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 如果需要认证的页面，先检查认证状态
  if (to.meta.requiresAuth) {
    if (authStore.isAuthenticated) {
      // 如果已有token，验证token是否有效
      try {
        const isValid = await authStore.checkAuth()
        if (!isValid) {
          // token无效，跳转到登录页
          next('/login')
          return
        }
      } catch (error) {
        // 验证过程中出错，也跳转到登录页
        console.error('认证检查失败:', error)
        next('/login')
        return
      }
    } else {
      // 没有token，直接跳转到登录页
      next('/login')
      return
    }
  }
  
  // 如果已经是登录状态但访问的是登录页，跳转到聊天页
  if (to.meta.requiresGuest && authStore.isAuthenticated) {
    next('/chat')
    return
  }
  
  next()
})

export default router